<template>
    <div class="good-container">
        <el-form ref="goodRowForm" v-model="goodRowForm" :inline="true">
            <el-form-item>
                <el-button size="mini" icon="el-icon-plus" @click="add" type="primary">新增</el-button>
            </el-form-item>
            <el-form-item>
                <el-input size="mini" v-model="name" @keyup.enter.native="updateTable" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button size="mini" @click="updateTable" type="primary">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-cascader size="mini" v-model="typeId" @change="change" clearable placeholder="请选择分类" :show-all-levels="false" :props="{ checkStrictly: true,label:'typeName',value:'typeId' }" :options="options"></el-cascader>
            </el-form-item>
        </el-form>

        <el-table :data="tableData" height="700" fit style="width:100%;margin:0 auto;">
            <el-table-column prop="goodId" label="商品id" min-width="150"></el-table-column>
            <el-table-column prop="aTypeName" label="一级分类" min-width="150" align="center"></el-table-column>
            <el-table-column prop="bTypeName" label="二级分类" min-width="150" align="center"></el-table-column>
            <el-table-column prop="goodName" label="商品名称" min-width="200" align="center"></el-table-column>
            <el-table-column prop="goodPrice" label="商品价格(￥)" min-width="120" align="center"></el-table-column>
            <el-table-column prop="goodPriceCheap" label="商品优惠价" min-width="100" align="center"></el-table-column>
            <!-- <el-table-column prop="goodIntro" label="商品简介" min-width="100" align="center"></el-table-column> -->
            <el-table-column label="商品小图" min-width="100" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.goodPicSmall == ''">暂无</span>
                    <el-image style="width:50px;height:50px" @click="addIntoPreviewList(base + scope.row.goodPicSmall)" :preview-src-list="previewList" fit="contain" v-else :src="base + scope.row.goodPicSmall"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="商品大图" min-width="100" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.goodPicLarge == ''">暂无</span>
                    <el-image style="width:50px;height:50px" @click="addIntoPreviewList(base + scope.row.goodPicLarge)" :preview-src-list="previewList" fit="contain" v-else :src="base + scope.row.goodPicLarge"></el-image>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="goodTypeCode" label="商品型号" min-width="100" align="center"></el-table-column>
            <el-table-column prop="goodCode" label="商品编码" min-width="100" align="center"></el-table-column> -->
            <el-table-column label="操作" fixed="right" min-width="200" align="center">
                <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="edit(scope.row)">编辑</el-button>
                    <el-button type="text" size="mini" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-drawer title="新增商品" size="70%" class="drawer" custom-class="test" :visible.sync="addDrawerShow" direction="rtl" :before-close="drawerBeforeClose">
            <el-form class="addGoodForm" ref="addGoodForm" label-width="80px" :rules="rules" :model="addGoodForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="上级类型" prop="preType">
                            <el-cascader v-model="addGoodForm.preType" clearable style="width:65%;" :props="{label:'typeName',value:'typeId',children:'children'}" :options="addGoodForm.options" placeholder="请选择分类级别"></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name">
                            <el-input type="text" v-model="addGoodForm.name" style="width:65%" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品品牌" prop="brand">
                            <el-input type="text" style="width:65%" v-model="addGoodForm.brand"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品排序" prop="order">
                            <el-input :min="0" type="number" style="width:65%" v-model="addGoodForm.order"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品价格" prop="price">
                            <el-input :min="0" type="number" style="width:65%" v-model="addGoodForm.price">
                                <template slot="append">￥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="会员价格" prop="cheapPrice">
                            <el-input :min="0" type="number" style="width:65%" v-model="addGoodForm.cheapPrice">
                                <template slot="append">￥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="商品总数" prop="number">
                            <el-input :min="0" type="number" style="width:65%" v-model="addGoodForm.sum"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label=""></el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品大图">
                            <el-upload class="upload-demo" :on-success="upSuccess1" :action="base+'upload/upload'">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品小图">
                            <el-upload class="upload-demo" :on-success="upSuccess2" :action="base+'upload/upload'">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" :offset="0">
                        <el-form-item class="center_item" label="商品描述">
                            <el-input type="textarea" v-model="addGoodForm.intro" :autosize="{minRows:3,maxRows:6}" :rows="5"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="footer">
                <el-button @click="addDrawerShow = false">取 消</el-button>
                <el-button type="primary" @click="addConfirm">提交</el-button>
            </div>
        </el-drawer>

        <el-drawer title="编辑商品" size="70%" class="drawer" custom-class="test" :visible.sync="editDrawerShow" direction="rtl" :before-close="drawerBeforeClose">
            <el-form class="editGoodForm" ref="editGoodForm" label-width="80px" :rules="rules2" :model="editGoodForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="上级类型" prop="preType">
                            <el-input type="text" v-model="editGoodForm.preType" disabled style="width:65%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name">
                            <el-input type="text" v-model="editGoodForm.name" style="width:65%" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品品牌" prop="brand">
                            <el-input type="text" style="width:65%" v-model="editGoodForm.brand"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品排序" prop="order">
                            <el-input :min="0" type="number" style="width:65%" v-model="editGoodForm.order"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品价格" prop="price">
                            <el-input :min="0" type="number" style="width:65%" v-model="editGoodForm.price">
                                <template slot="append">￥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="会员价格" prop="cheapPrice">
                            <el-input :min="0" type="number" style="width:65%" v-model="editGoodForm.cheapPrice">
                                <template slot="append">￥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="商品总数" prop="sum">
                            <el-input :min="0" type="number" style="width:65%" v-model="editGoodForm.sum"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label=""></el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品大图">
                            <el-upload class="upload-demo" :on-success="upSuccess3" :action="base+'upload/upload'">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="center_item" label="商品小图">
                            <el-upload class="upload-demo" :on-success="upSuccess4" :action="base+'upload/upload'">
                                <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24" :offset="0">
                        <el-form-item class="center_item" label="商品描述">
                            <el-input type="textarea" v-model="editGoodForm.intro" :autosize="{minRows:3,maxRows:6}" :rows="5"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="footer">
                <el-button @click="addDrawerShow = false">取 消</el-button>
                <el-button type="primary" @click="editConfirm">提交</el-button>
            </div>
        </el-drawer>

        <!-- 分页 -->
        <el-row class="flex_center" :gutter="20">
            <el-col class="flex_center" :span="3" :offset="0">
                <el-button @click="prev" icon="el-icon-arrow-left"></el-button>
            </el-col>
            <el-col class="flex_center" :span="8" :offset="0">
                <span>每页显示</span>
                <el-input-number v-model="num" @change="handleChangeNum" :min="1" label="描述文字"></el-input-number>
                <span>个</span>
            </el-col>
            <el-col class="flex_center" :span="8" :offset="0">
                <span>当前在</span>
                <el-input-number v-model="page" @change="handleChangePage" :min="1" :max="Math.ceil(totalNum / num)" label="描述文字"></el-input-number>
                <span>页</span>
            </el-col>
            <el-col class="flex_center" :span="2" :offset="0">
                <div>共{{totalNum}}条数据</div>
            </el-col>
            <el-col class="flex_center" :span="3" :offset="0">
                <el-button @click="next" icon="el-icon-arrow-right"></el-button>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { getTypeOptions } from "@/api/type";
import { getAllGoods, delGoods, addGoods } from "@/api/good";
export default {
    data() {
        var vOrder = (rule, value, callback) => {
            if (value == undefined) {
                return callback(new Error("请输入商品排序"));
            } else if (!value || "" == value.trim()) {
                return callback(new Error("请输入合适的排序"));
            } else {
                callback();
            }
        };
        var vNumber = (rule, value, callback) => {
            if (!value || "" == value.trim()) {
                return callback(new Error("请输入商品总数"));
            } else if (value <= 0) {
                return callback(new Error("请输入合适的商品总数"));
            } else {
                callback();
            }
        };
        var vPrice = (rule, value, callback) => {
            if (!value || "" == value.trim()) {
                return callback(new Error("请输入商品价格"));
            } else if (value <= 0) {
                return callback(new Error("请输入合适的商品价格"));
            } else {
                callback();
            }
        };
        var vPriceCheap = (rule, value, callback) => {
            if (!value || "" == value.trim()) {
                return callback(new Error("请输入会员价格"));
            } else if (!this.addGoodForm.price) {
                this.$refs.addGoodForm.validateField("price");
            } else if (
                Number(value) <= 0 ||
                Number(this.addGoodForm.price) < Number(value)
            ) {
                return callback(new Error("请输入合适的会员价格"));
            } else {
                callback();
            }
        };
        var vEditPrice = (rule, value, callback) => {
            if (!value || "" == value.trim()) {
                return callback(new Error("请输入商品价格"));
            } else if (value <= 0) {
                return callback(new Error("请输入合适的商品价格"));
            } else {
                callback();
            }
        };
        var vEditPriceCheap = (rule, value, callback) => {
            if (!value || "" == value.trim()) {
                return callback(new Error("请输入会员价格"));
            } else if (!this.editGoodForm.price) {
                this.$refs.editGoodForm.validateField("price");
            } else if (
                Number(value) <= 0 ||
                Number(this.editGoodForm.price) < Number(value)
            ) {
                return callback(new Error("请输入合适的会员价格"));
            } else {
                callback();
            }
        };
        var vEditSum = (rule, value, callback) => {
            if (value == undefined) {
                return callback(new Error("请输入商品总数"));
            } else if (value < 0) {
                return callback(new Error("请输入合适的商品总数"));
            } else {
                callback();
            }
        };
        var vEditOrder = (rule, value, callback) => {
            if (value == undefined) {
                return callback(new Error("请输入商品排序"));
            } else if (value < 0) {
                return callback(new Error("请输入合适的商品排序"));
            } else {
                callback();
            }
        };
        return {
            base: "http://localhost:3000/",
            previewList: [""],
            rules: {
                preType: [
                    {
                        required: true,
                        message: "请选择上级类型",
                        trigger: "blur",
                    },
                ],
                name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                brand: [
                    {
                        required: true,
                        message: "请输入品牌名称",
                        trigger: "blur",
                    },
                ],
                order: [{ validator: vOrder, trigger: "blur", required: true }],
                price: [{ validator: vPrice, trigger: "blur", required: true }],
                cheapPrice: [
                    { validator: vPriceCheap, trigger: "blur", required: true },
                ],
                number: [
                    { validator: vNumber, trigger: "blur", required: true },
                ],
            },
            rules2: {
                name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                brand: [
                    {
                        required: true,
                        message: "请输入商品品牌",
                        trigger: "blur",
                    },
                ],
                price: [
                    {
                        validator: vEditPrice,
                        trigger: "blur",
                        required: true,
                    },
                ],
                cheapPrice: [
                    {
                        validator: vEditPriceCheap,
                        trigger: "blur",
                        required: true,
                    },
                ],
                sum: [
                    {
                        validator: vEditSum,
                        trigger: "blur",
                        required: true,
                    },
                ],
                order: [
                    {
                        validator: vEditOrder,
                        trigger: "blur",
                        required: true,
                    },
                ],
            },
            addGoodForm: {
                name: "",
                preType: "",
                options: [
                    {
                        typeId: "0",
                        typeName: "主类目",
                        children: [],
                    },
                ],
                order: 0,
                price: "",
                cheapPrice: "",
                brand: "",
                sum: "",
                goodPicLarge: "",
                goodPicSmall: "",
                intro: "",
            },
            editGoodForm: {
                name: "",
                preType: "",
                aTypeId: "",
                bTypeId: "",
                order: 0,
                price: "",
                cheapPrice: "",
                brand: "",
                sum: "",
                goodPicLarge: "",
                goodPicSmall: "",
                intro: "",
            },
            addDrawerShow: false,
            editDrawerShow: false,
            goodRowForm: {},
            name: "",
            typeId: "",
            aTypeId: "",
            bTypeId: "",
            options: [],
            page: 1,
            num: 15,
            tableData: [],
            totalNum: 0,
        };
    },
    mounted() {
        this.updateOptions();
        this.updateTable();
    },
    methods: {
        // 抽屉关闭前的回调
        drawerBeforeClose(done) {
            if (this.addDrawerShow) {
                this.$refs.addGoodForm.resetFields();
                done();
            } else if (this.editDrawerShow) {
                this.$refs.editGoodForm.resetFields();
                done();
            } else {
                done();
            }
        },
        // 新增确定
        addConfirm() {
            this.$refs.addGoodForm.validate((valid) => {
                // console.log(this.addGoodForm.goodPicSmall);
                // console.log(this.addGoodForm.goodPicLarge);
                if (valid) {
                    let ndata = {
                        aTypeId: this.addGoodForm.preType[1],
                        bTypeId: this.addGoodForm.preType[2],
                        goodName: this.addGoodForm.name,
                        goodBrand: this.addGoodForm.brand,
                        goodOrder: this.addGoodForm.order,
                        goodPrice: this.addGoodForm.price,
                        goodPriceCheap: this.addGoodForm.cheapPrice,
                        goodIntro: this.addGoodForm.intro,
                        goodPicSmall: this.addGoodForm.goodPicSmall,
                        goodPicLarge: this.addGoodForm.goodPicLarge,
                    };
                    addGoods(ndata).then((e) => {
                        if (e.data.code == "0") {
                            this.$message.success(e.data.message);
                            this.updateTable();
                        } else {
                            this.$message.error(e.data.message);
                        }
                        this.addDrawerShow = false;
                    });
                } else {
                    return false;
                }
            });
        },
        // 新增确定
        editConfirm() {
            this.$refs.editGoodForm.validate((valid) => {
                // console.log(this.addGoodForm.goodPicSmall);
                // console.log(this.addGoodForm.goodPicLarge);
                if (valid) {
                    let ndata = {
                        aTypeId: this.editGoodForm.aTypeId,
                        bTypeId: this.editGoodForm.bTypeId,
                        goodName: this.editGoodForm.name,
                        goodBrand: this.editGoodForm.brand,
                        goodOrder: this.editGoodForm.order,
                        goodPrice: this.editGoodForm.price,
                        goodPriceCheap: this.editGoodForm.cheapPrice,
                        goodIntro: this.editGoodForm.intro,
                        goodPicSmall: this.editGoodForm.goodPicSmall,
                        goodPicLarge: this.editGoodForm.goodPicLarge,
                    };
                    console.log(ndata);
                    // addGoods(ndata).then((e) => {
                    //     if (e.data.code == "0") {
                    //         this.$message.success(e.data.message);
                    //         this.updateTable();
                    //     } else {
                    //         this.$message.error(e.data.message);
                    //     }
                    //     this.addDrawerShow = false;
                    // });
                } else {
                    return false;
                }
            });
        },
        // 新增时的大图上传
        upSuccess1(e, file, fileList) {
            console.log(e);
            if (e.code == "0") {
                this.addGoodForm.goodPicLarge = e.path;
                this.$message.success(e.message);
            } else {
                this.$message.error(e.message);
            }
        },
        // 新增时的小图上传
        upSuccess2(e, file, fileList) {
            if (e.code == "0") {
                this.addGoodForm.goodPicSmall = e.path;
                this.$message.success(e.message);
            } else {
                this.$message.error(e.message);
            }
        },
        // 修改时的大图上传
        upSuccess3(e, file, fileList) {
            console.log(e);
            if (e.code == "0") {
                this.editGoodForm.goodPicLarge = e.path;
                this.$message.success(e.message);
            } else {
                this.$message.error(e.message);
            }
        },
        // 修改时的小图上传
        upSuccess4(e, file, fileList) {
            if (e.code == "0") {
                this.editGoodForm.goodPicSmall = e.path;
                this.$message.success(e.message);
            } else {
                this.$message.error(e.message);
            }
        },
        addDrawerClose() {
            this.$confirm("确认关闭？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then((e) => {
                    this.addDrawerShow = false;
                })
                .catch((e) => {});
        },
        // 单点新增
        add() {
            this.addDrawerShow = true;
        },
        // 单点删除
        del(row) {
            this.$confirm(`确定删除商品 '${row.goodName}' 吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    let ndata = [];
                    ndata.push({
                        aTypeId: row.aTypeId,
                        bTypeId: row.bTypeId,
                        goodId: row.goodId,
                    });
                    delGoods({
                        ids: ndata,
                    }).then((e) => {
                        if (e.data.code == "0") {
                            this.$message.success(e.data.message);
                            this.updateTable();
                        } else {
                            this.message.error(e.data.message);
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: "success",
                        message: "已取消",
                    });
                });
        },
        // 单点编辑
        edit(row) {
            console.log(this.addGoodForm.options);
            console.log(row);
            this.editGoodForm.preType = `主类目 / ${row.aTypeName} / ${row.bTypeName}`;
            this.editGoodForm.aTypeId = row.aTypeId;
            this.editGoodForm.bTypeId = row.bTypeId;
            // getMenuArr(row.aTypeId,row.bTypeId)
            this.editGoodForm.name = row.goodName;
            this.editGoodForm.brand = row.goodBrand;
            this.editGoodForm.brand = row.goodOrder;
            this.editGoodForm.price = row.goodPrice;
            this.editGoodForm.cheapPrice = row.goodPriceCheap;
            this.editGoodForm.sum = row.goodNum;
            console.log(this.editGoodForm);
            this.editDrawerShow = true;
        },
        // 级联选择器 值变化
        change(val) {
            if (val.length == 1) {
                this.aTypeId = val[0];
                this.bTypeId = "";
            } else if (val.length == 2) {
                this.aTypeId = val[0];
                this.bTypeId = val[1];
            } else {
                this.aTypeId = "";
                this.bTypeId = "";
            }
            this.updateTable();
        },
        updateOptions() {
            getTypeOptions().then((e) => {
                if (e.data.code == "0") {
                    this.options = e.data.data;
                    this.addGoodForm.options[0].children = e.data.data;
                } else {
                    this.$message.error(e.data.message);
                }
            });
        },
        updateTable() {
            let ndata = {
                goodName: this.name,
                aTypeId: this.aTypeId,
                bTypeId: this.bTypeId,
                page: this.page,
                num: this.num,
            };
            getAllGoods(ndata).then((e) => {
                if (e.data.code == "0") {
                    this.tableData = e.data.data;
                    this.totalNum = e.data.sum;
                } else {
                    this.$message.success(e.data.message);
                }
            });
        },
        // 更新待预览图片
        addIntoPreviewList(url) {
            this.previewList = [url];
        },
        // 分页相关
        prev() {
            if (this.page == 1) {
                this.$message.error("当前已是第一页");
            } else {
                this.page--;
                this.updateTable();
            }
        },
        next() {
            if (this.page < Math.ceil(this.totalNum / this.num)) {
                this.page++;
                this.updateTable();
            } else {
                this.$message.error("当前已是最后一页了");
            }
        },
        // 每页显示个数变化
        handleChangeNum() {
            this.page = 1;
            this.updateTable();
        },
        // 页码变化
        handleChangePage() {
            this.updateTable();
        },
    },
};
</script>

<style scoped>
.good-container {
    padding: 20px;
}

.flex_center {
    margin-top: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

.flex_center div,
.flex_center span {
    font-family: sans-serif;
    font-size: 14px;
    margin: 0 5px;
}

.addGoodForm,
.editGoodForm {
    margin: 0 20px;
}

.footer {
    position: absolute;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    bottom: 100px;
    width: 100%;
}
</style>